import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/sequelize';
import { RESPONSE_CODE } from "@/enums/code";
import { getImgInfo } from "@/utils/img";
import { Tenant } from './tenant.model';
import { ThemeConfig } from './themeConfig.model'
import { SysConfig } from './sysConfig.model'
import { getPageWhere, getPageData, } from '@/utils/page'
import { AddTenantDto, GetTenantPageDto, UpdateBaseInfoConfigDto } from './tenant.dto'


@Injectable()
export class TenantService {
  constructor(

    @InjectModel(Tenant)
    private tenantModel: typeof Tenant,

    @InjectModel(ThemeConfig)
    private themeConfigModel: typeof ThemeConfig,

    @InjectModel(SysConfig)
    private sysConfigModel: typeof SysConfig,

  ) { }

  async getTenantPublicById(id: string) {
    const currentTheme =
      (await this.themeConfigModel.findOne({ where: { tenantId: id } })) ||
      (await this.themeConfigModel.findOne({ where: { tenantId: -1 } }));
    const configRes = await this.sysConfigModel.findByPk(1);
    let data = {}
    if (currentTheme) {
      data['themeConfig'] = currentTheme?.dataValues.themeConfig
    }
    if (configRes) {
      const { appLoginBgImg, icon, loginBgImg, logo, logo2, loginFrameBgImg } =
        configRes?.dataValues;
      data = {
        ...data,
        ...configRes?.dataValues,
        appLoginBgImg: getImgInfo(appLoginBgImg),
        loginFrameBgImg: getImgInfo(loginFrameBgImg),
        icon: getImgInfo(icon),
        loginBgImg: getImgInfo(loginBgImg),
        logo: getImgInfo(logo),
        logo2: getImgInfo(logo2),
      }
    }

    return {
      code: RESPONSE_CODE.SUCCESS,
      data: data,
      msg: null,
    }
  }

  async getTenantPublicInfoByDomain(domain: string) {
    const res = await this.tenantModel.findAll();
    if (res === null) {
      return {
        code: RESPONSE_CODE.SUCCESS,
        data: null,
        msg: null,
      };
      ;
    }
    const configRes = await this.sysConfigModel.findByPk(1);
    const themeRes = await this.themeConfigModel.findOne({
      where: { tenantId: -1 },
    });

    const { appLoginBgImg, icon, loginBgImg, logo, logo2 } =
      configRes?.dataValues;
    const config = {
      ...configRes?.dataValues,
      appLoginBgImg: getImgInfo(appLoginBgImg),
      icon: getImgInfo(icon),
      loginBgImg: getImgInfo(loginBgImg),
      logo: getImgInfo(logo),
      logo2: getImgInfo(logo2),
      themeConfig: themeRes?.dataValues?.themeConfig ?? {},
    };
    const data = res.map((item) => {
      const { id, name, tenantDomain } = item.dataValues;
      return {
        id,
        name,
        domain: tenantDomain,
        loginMode: 1,
        config,
      };
    });
    return {
      code: RESPONSE_CODE.SUCCESS,
      data,
      msg: null,
    }
  }

  /**
   * 添加租户
   * @method post
   * @param tenant
   */
  async addTenant(addTenantDto: AddTenantDto) {
    const { name, code, tenantDomain, startTime, endTime, status, menuId } = addTenantDto

    await this.tenantModel.create({
      name,
      code,
      domain: tenantDomain,
      startTime,
      endTime,
      status,
      menuId,
    });
    return {
      code: RESPONSE_CODE.SUCCESS,
      data: null,
      msg: null,
    };
  }

  /**
   * 获取租户分页列表
   * @method get
   * @param tenant
   */
  async getTenantPage(getTenantPageDto: GetTenantPageDto) {
    const { current, size, descs } = getTenantPageDto

    const { count, rows } = await this.tenantModel.findAndCountAll({
      order: descs ? [["createTime", "DESC"]] : [],
      ...getPageWhere(current, size),
    });
    return {
      code: RESPONSE_CODE.SUCCESS,
      data: getPageData(current, size, count, rows),
      msg: null,
    };
  }

  /**
   * 获取 base config
   * @method get
   * @param tenantId number
   */
  async getTenantConfigByKey(key: string, tenantId: number) {
    console.log('getTenantConfigByKey', key, tenantId)
    const sysConfig = await this.sysConfigModel.findOne({ where: { tenantId } });
    const themeConfig = await this.themeConfigModel.findAll();

    const currentTheme =
      themeConfig.find((item) => item.dataValues.tenantId === tenantId) ??
      themeConfig.find((item) => item.dataValues.tenantId === -1);

    let data = {};
    if (sysConfig) {
      const { appLoginBgImg, icon, loginBgImg, logo, logo2, loginFrameBgImg } =
        sysConfig.dataValues;

      data = {
        ...sysConfig.dataValues,
        appLoginBgImg: getImgInfo(appLoginBgImg),
        loginFrameBgImg: getImgInfo(loginFrameBgImg),
        icon: getImgInfo(icon),
        loginBgImg: getImgInfo(loginBgImg),
        logo: getImgInfo(logo),
        logo2: getImgInfo(logo2),
        themeConfig: currentTheme?.dataValues.themeConfig,
      };
    }
    return {
      code: RESPONSE_CODE.SUCCESS,
      data: data,
      msg: null,
    }
  }

  /**
   * 更新 base config
   * @method post
   * @param tenantId number
   * @param updateBaseInfoConfigDto 
   */
  async updateBaseInfoConfig(tenantId: number, updateBaseInfoConfigDto?: UpdateBaseInfoConfigDto,) {
    if (updateBaseInfoConfigDto?.themeConfig) {
      const [record, created] = await this.themeConfigModel.findOrCreate({
        where: { tenantId },
        defaults: {
          tenantId,
          themeConfig: updateBaseInfoConfigDto.themeConfig,
        },
      });
      if (!created) {
        await record.update({
          themeConfig: updateBaseInfoConfigDto.themeConfig,
        });
      }
    } else {
      const [record, created] = await this.sysConfigModel.findOrCreate({
        where: { tenantId },
        defaults: {
          ...updateBaseInfoConfigDto,
          tenantId,
          appLoginBgImg: updateBaseInfoConfigDto?.appLoginBgImg?.url,
          icon: updateBaseInfoConfigDto?.icon?.url,
          loginBgImg: updateBaseInfoConfigDto?.loginBgImg?.url,
          logo: updateBaseInfoConfigDto?.logo?.url,
          logo2: updateBaseInfoConfigDto?.logo2?.url,
          loginFrameBgImg: updateBaseInfoConfigDto?.loginFrameBgImg?.url,
        },
      });
      if (!created) {
        await record.update({
          ...updateBaseInfoConfigDto,
          appLoginBgImg: updateBaseInfoConfigDto?.appLoginBgImg?.url,
          icon: updateBaseInfoConfigDto?.icon?.url,
          loginBgImg: updateBaseInfoConfigDto?.loginBgImg?.url,
          logo: updateBaseInfoConfigDto?.logo?.url,
          logo2: updateBaseInfoConfigDto?.logo2?.url,
          loginFrameBgImg: updateBaseInfoConfigDto?.loginFrameBgImg?.url,
        });
      }
    }
    return {
      code: RESPONSE_CODE.SUCCESS,
      data: [],
      msg: null,
    }
  }
}
